import React, { useState, useEffect } from 'react'
import { Card, Row, Col, List, Tag, Progress, Space, Typography, Spin, Button, Badge } from 'antd'
import {
  FireOutlined,
  RiseOutlined,
  FallOutlined,
  MinusOutlined,
  BulbOutlined,
  TrophyOutlined
} from '@ant-design/icons'
import LineChart from '../../components/Charts/LineChart'
import WordCloud from '../../components/Charts/WordCloud'
import PieChart from '../../components/Charts/PieChart'
import { HotTopic, ContentSuggestion } from '../../../types/hotspot'
import { MediaPlatform } from '../../../types/mediaData'
import {
  generateKeywordData,
  generateContentSuggestions,
  generateHotspotTrends,
  PLATFORM_META
} from '../../../services/mock/mediaDataMock'
import { fetchHotTopicsFromWeb, refreshHotTopics } from '../../../services/hotspot/hotspotService'

const { Title, Paragraph, Text } = Typography

/**
 * 热点分析页面
 * 展示热点话题监控和创作建议
 */
const HotspotAnalysisPage: React.FC = () => {
  const [loading, setLoading] = useState(true)
  const [hotTopics, setHotTopics] = useState<HotTopic[]>([])
  const [suggestions, setSuggestions] = useState<ContentSuggestion[]>([])

  // 从热点话题中提取关键词生成词云数据 - 必须在所有条件判断之前
  const keywordData = React.useMemo(() => {
    if (hotTopics.length === 0) return []

    console.log('[热点分析] 开始生成关键词云数据，热点数量:', hotTopics.length)

    const keywords = hotTopics.flatMap(topic => {
      console.log('[热点分析] 话题:', topic.title, '关键词:', topic.keywords)
      return topic.keywords.map(keyword => ({
        name: keyword,
        value: Math.floor(Math.random() * 50) + 20 // 20-70之间的随机值
      }))
    }).reduce((acc, curr) => {
      const existing = acc.find(item => item.name === curr.name)
      if (existing) {
        existing.value += curr.value
      } else {
        acc.push(curr)
      }
      return acc
    }, [] as Array<{ name: string; value: number }>)

    console.log('[热点分析] 生成的关键词数据:', keywords)
    return keywords
  }, [hotTopics])

  useEffect(() => {
    loadHotTopics()
  }, [])

  const loadHotTopics = async () => {
    setLoading(true)
    try {
      // 从互联网获取真实热点数据
      const topics = await fetchHotTopicsFromWeb()
      setHotTopics(topics)
      setSuggestions(generateContentSuggestions())
    } catch (error) {
      console.error('加载热点数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleRefresh = async () => {
    await loadHotTopics()
  }

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100%',
        minHeight: '400px'
      }}>
        <Spin size="large" tip="加载数据中..." />
      </div>
    )
  }

  const hotspotTrends = generateHotspotTrends(hotTopics)

  // 按热度排序取前10
  const topHotTopics = [...hotTopics].sort((a, b) => b.heat - a.heat).slice(0, 10)

  // 折线图数据 - 热点趋势
  const trendChartSeries = hotspotTrends.map(trend => ({
    name: trend.topic,
    data: trend.data,
    color: undefined // 使用默认颜色
  }))

  // 饼图数据 - 平台分布
  const platformDistribution = Object.values(MediaPlatform).map(platform => {
    const count = hotTopics.filter(t => t.platform === platform).length
    return {
      name: PLATFORM_META[platform].name,
      value: count,
      color: PLATFORM_META[platform].color
    }
  }).filter(item => item.value > 0)

  // 趋势图标
  const getTrendIcon = (trend: string) => {
    switch (trend) {
      case 'up':
        return <RiseOutlined style={{ color: '#52c41a', fontSize: 16 }} />
      case 'down':
        return <FallOutlined style={{ color: '#f5222d', fontSize: 16 }} />
      default:
        return <MinusOutlined style={{ color: '#faad14', fontSize: 16 }} />
    }
  }

  const getTrendColor = (trend: string) => {
    switch (trend) {
      case 'up':
        return '#52c41a'
      case 'down':
        return '#f5222d'
      default:
        return '#faad14'
    }
  }

  return (
    <div style={{
      padding: '32px 48px',
      height: '100%',
      overflow: 'auto',
      background: '#f5f5f5'
    }}>
      {/* 页面标题 */}
      <div style={{ marginBottom: 32, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={2} style={{ marginBottom: 8 }}>热点分析</Title>
          <Paragraph type="secondary" style={{ fontSize: 16 }}>
            实时热点监控和创作建议，数据每日更新
          </Paragraph>
        </div>
        <Button
          type="primary"
          icon={<FireOutlined />}
          onClick={handleRefresh}
          loading={loading}
        >
          刷新热点
        </Button>
      </div>

      {/* 主要内容区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {/* 热度榜单 */}
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <FireOutlined style={{ color: '#f5222d' }} />
                <span>热度榜单 TOP 10</span>
              </Space>
            }
            variant="borderless"
            styles={{ body: { padding: 0, maxHeight: '600px', overflow: 'auto' } }}
          >
            <List
              dataSource={topHotTopics}
              renderItem={(item, index) => (
                <List.Item
                  style={{ padding: '16px 24px' }}
                  extra={
                    <Space>
                      {getTrendIcon(item.trend)}
                      {item.changeRate !== undefined && (
                        <Text style={{ color: getTrendColor(item.trend) }}>
                          {item.changeRate > 0 ? '+' : ''}{item.changeRate.toFixed(1)}%
                        </Text>
                      )}
                    </Space>
                  }
                >
                  <List.Item.Meta
                    avatar={
                      <Badge
                        count={index + 1}
                        style={{
                          backgroundColor: index < 3 ? '#f5222d' : '#999',
                          fontSize: 14,
                          fontWeight: 'bold',
                          minWidth: 24,
                          height: 24,
                          lineHeight: '24px'
                        }}
                      />
                    }
                    title={
                      <Space>
                        <Text strong>{item.title}</Text>
                        <Tag color={PLATFORM_META[item.platform].color} style={{ marginLeft: 8 }}>
                          {PLATFORM_META[item.platform].name}
                        </Tag>
                      </Space>
                    }
                    description={
                      <div>
                        <div style={{ marginBottom: 8 }}>
                          <Space size={4}>
                            {item.keywords.slice(0, 4).map((keyword, idx) => (
                              <Tag key={idx} style={{ fontSize: 11 }}>
                                {keyword}
                              </Tag>
                            ))}
                          </Space>
                        </div>
                        <Progress
                          percent={item.heat}
                          size="small"
                          strokeColor={{
                            '0%': '#ff4d4f',
                            '100%': '#faad14'
                          }}
                          showInfo={false}
                        />
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 创作建议 */}
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <BulbOutlined style={{ color: '#faad14' }} />
                <span>创作建议</span>
              </Space>
            }
            variant="borderless"
            styles={{ body: { maxHeight: '600px', overflow: 'auto' } }}
          >
            <List
              dataSource={suggestions}
              renderItem={(item) => (
                <List.Item style={{ alignItems: 'flex-start' }}>
                  <List.Item.Meta
                    avatar={
                      <TrophyOutlined style={{ fontSize: 24, color: '#1890ff', marginTop: 4 }} />
                    }
                    title={
                      <div>
                        <Text strong style={{ fontSize: 15 }}>{item.title}</Text>
                        <div style={{ marginTop: 4 }}>
                          <Space size={4}>
                            {item.platform.map((p, idx) => (
                              <Tag key={idx} color={PLATFORM_META[p].color} style={{ fontSize: 11 }}>
                                {PLATFORM_META[p].name}
                              </Tag>
                            ))}
                          </Space>
                        </div>
                      </div>
                    }
                    description={
                      <div>
                        <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                          {item.reason}
                        </Text>
                        <Space size={4}>
                          {item.keywords.map((keyword, idx) => (
                            <Tag key={idx} color="blue" style={{ fontSize: 11 }}>
                              {keyword}
                            </Tag>
                          ))}
                        </Space>
                        <div style={{ marginTop: 8 }}>
                          <Progress
                            percent={item.heat}
                            size="small"
                            strokeColor="#52c41a"
                            format={(percent) => `热度 ${percent}`}
                          />
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={16}>
          <Card title="热点趋势变化" variant="borderless">
            <LineChart
              series={trendChartSeries}
              height={400}
              yAxisName="热度值"
            />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="平台热点分布" variant="borderless">
            <PieChart
              data={platformDistribution}
              height={400}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24}>
          <Card title="热门关键词云" variant="borderless">
            <div style={{ padding: '20px', background: '#fafafa', borderRadius: '8px' }}>
              {keywordData.length > 0 ? (
                <>
                  <div style={{ marginBottom: 16, color: '#666', fontSize: 14 }}>
                    共 {keywordData.length} 个关键词
                  </div>
                  {/* 备用方案：标签云 */}
                  <div style={{
                    display: 'flex',
                    flexWrap: 'wrap',
                    gap: '16px 24px',
                    minHeight: 400,
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '40px'
                  }}>
                    {keywordData.slice().sort((a, b) => b.value - a.value).map((item, index) => {
                      const maxValue = Math.max(...keywordData.map(d => d.value), 1)
                      const fontSize = 16 + (item.value / maxValue) * 40
                      const colors = [
                        '#1890ff', '#52c41a', '#faad14', '#f5222d',
                        '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16',
                        '#2f54eb', '#a0d911'
                      ]
                      return (
                        <span
                          key={index}
                          style={{
                            fontSize: `${fontSize}px`,
                            color: colors[index % colors.length],
                            fontWeight: 600,
                            cursor: 'pointer',
                            transition: 'all 0.3s',
                            textShadow: '0 2px 4px rgba(0,0,0,0.1)',
                            lineHeight: 1.5
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.transform = 'scale(1.1)'
                            e.currentTarget.style.textShadow = '0 4px 8px rgba(0,0,0,0.2)'
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.transform = 'scale(1)'
                            e.currentTarget.style.textShadow = '0 2px 4px rgba(0,0,0,0.1)'
                          }}
                        >
                          {item.name}
                        </span>
                      )
                    })}
                  </div>
                </>
              ) : (
                <div style={{
                  height: 400,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#999'
                }}>
                  暂无关键词数据
                </div>
              )}
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default HotspotAnalysisPage
